import { NextResponse } from "next/server";
import userModule from '@/modules/user'
import bcrypt from "bcryptjs";
import jwt from '@/utils/jwt'
import { AUTH_TOKEN } from "@/config/settings";
import verifyCode from "@/lib/verify-code";
import isEmail from "@/lib/isemail";

export async function POST(request) {
  const codeMap = { 0: '超级管理员注册成功,账号验证中......', 1: '普通管理员注册成功,账号验证中......', 2: '普通用户注册成功，等待超级管理员审核......', 3: '用户名已存在,请返回登录页进行登录', 4: '用户已存在，等待超级管理员审核通过后登录', 5: '创建用户失败', 6: '验证码错误', 7: '账号必须是邮箱', 8: '账号或密码不能为空' };
  const { username, password, status, nickname = '未设置用户名', avatar = '', mobile = '', email = '', role_id, verificationCode } = await request.json();
  if (!username || !password) return NextResponse.json({ message: "Username and password are required", code: 8, codeMap }, { status: 400 });
  if (!isEmail(username)) return NextResponse.json({ message: "Email format is incorrect", code: 7, codeMap }, { status: 400 });
  const [countResult] = await userModule.count();
  const userCount = countResult.count || countResult['COUNT(*)'] || 0;
  if (userCount === 0) {
    const verifiy = verifyCode(username, verificationCode);
    if (verifiy.status === false) return NextResponse.json({ message: "Verification code error", code: 6, codeMap }, { status: 400 });
    const hashedPassword = await bcrypt.hash(password, 10);
    const result = await userModule.post(username, hashedPassword, 0, nickname, avatar, mobile, email, 1); // username,password,status, nickname, avatar, role_id
    if (result.affectedRows === 1) return NextResponse.json({ message: "Super admin created", code: 0, codeMap }, { status: 200 });
    return NextResponse.json({ message: "Error creating user", code: 5, codeMap }, { status: 500 });
  }

  const token = request.cookies.get(AUTH_TOKEN)?.value;
  let isSuperAdmin = false;
  let currentUser = null;
  if (token) {
    try {
      const payload = await jwt.verify(token);
      currentUser = payload?.payload?.username;
      const dbUser = await userModule.get(currentUser);
      if (dbUser && dbUser?.roleInfo?.code === 0) {
        isSuperAdmin = true;
      }
    } catch (e) { }
  }

  const userInfo = await userModule.get(username);
  if (userInfo && userInfo?.status === 0) return NextResponse.json({ message: "Username already exists", code: 3, codeMap }, { status: 409 });
  if (userInfo && userInfo?.status === 1) return NextResponse.json({ message: "Username already exists, It requires review by a super administrator", code: 4, codeMap }, { status: 409 });

  const finalRoleId = isSuperAdmin ? (role_id ? Number(role_id) : 2) : 2;
  const finalStatus = isSuperAdmin ? (status !== undefined && status !== null ? Number(status) : 0) : 1;

  const verifiy = verifyCode(username, verificationCode);
  if (verifiy.status === false) return NextResponse.json({ message: "Verification code error", code: 6, codeMap }, { status: 400 });

  const hashedPassword = await bcrypt.hash(password, 10);
  const result = await userModule.post(username, hashedPassword, finalStatus, nickname, avatar, mobile, email, finalRoleId);
  if (result.affectedRows === 1) {
    if (isSuperAdmin) {
      return NextResponse.json({ message: "User created successfully", code: 1, codeMap }, { status: 200 });
    } else {
      return NextResponse.json({ message: "User created successfully, It requires review by a super administrator", code: 2, codeMap }, { status: 200 });
    }
  }
  return NextResponse.json({ message: "Error creating user", code: 5, codeMap }, { status: 500 });
}